package com.springbootblog.utils;

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.springbootblog.pojo.Article;
import org.json.JSONException;
import org.json.JSONObject;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import com.google.gson.Gson;

public class Function
{
    /**
     * json字符串转map
     * @param json
     * @return
     */
    public static Map<String, Object> convertJsonToMap(String json)
    {
        ObjectMapper objectMapper = new ObjectMapper();
        try
        {
            return objectMapper.readValue(json, Map.class);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 设置Sentinel规则
     * 使用代码编写流控规则，项目中不推荐使用，这是硬编码方式 官方推荐使用控制台页面进行设置
     * @param resource
     * @param number
     */
    public static void setSentinelRule(String resource,Integer number)
    {
        /* 1.创建存放限流规则的集合 */
        List<FlowRule> rules = new ArrayList<>();
        /* 2.创建限流规则 */
        FlowRule rule = new FlowRule();
        /* 定义资源，表示 Sentinel 会对哪个资源生效 "AddUser" */
        rule.setResource(resource);
        /* 定义限流的类型(此处使用 QPS 作为限流类型) */
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        /* 定义 QPS 每秒通过的请求数 1 */
        rule.setCount(number);
        /* 3.将限流规则存放到集合中 */
        rules.add(rule);
        /* 4.加载限流规则 */
        FlowRuleManager.loadRules(rules);
    }

    /**
     * 获取分页页码
     * @param page      start
     * @param pageSize  limit
     * @return
     */
    public static Map<String,Integer> getStartNumByPage(Integer page, Integer pageSize)
    {
        if(pageSize == null)
        {
            pageSize = 10;
        }
        int num = 0;
        if (page == null || page <= 1)
        {
            num = 0;
        }
        else
        {
            page = page - 1;
            num = page * pageSize;
        }
        // 创建一个HashMap对象
        Map<String,Integer> pageInfo =  new HashMap<>();
        // 添加键值对
        pageInfo.put("page",num);
        pageInfo.put("pageSize",pageSize);
        //获取键值对
        //int page = pageInfo.get("page");/10
        //int pageSize = pageInfo.get("pageSize");//20
        return pageInfo;
    }

    /**
     * 删除字符串前后指定字符
     * @param
     * @return
     */
    public static String removeStrChars(String str,char chars)
    {
        if (str == null || str.isEmpty()) {
            return str;
        }

        int start = 0;
        int end = str.length() - 1;

        // 去除开头的特定符号
        while (start <= end && str.charAt(start) == chars) {
            start++;
        }

        // 去除尾部的特定符号
        while (start <= end && str.charAt(end) == chars) {
            end--;
        }

        return str.substring(start, end + 1);
    }

    /**
     * 获取当前访问ip
     * @param request
     * @return
     */
    public static String getIpAddress(HttpServletRequest request)
    {
        String ipAddress = request.getHeader("X-Forwarded-For");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }
        if (ipAddress != null && ipAddress.indexOf(",") != -1) {
            ipAddress = ipAddress.split(",")[0];
        }
        return ipAddress;
    }

    /**
     * 获取两个日期之间的天数
     * @param startDate
     * @param endDate
     * @return
     */
    public static long getDaysBetween(LocalDate startDate, LocalDate endDate)
    {
        return ChronoUnit.DAYS.between(startDate, endDate);
    }

    /**
     * 格式化当前时间
     * @param format（yyyy-MM-dd / yyyy-MM-dd H:m:s）
     * @return
     */
    public static String getCurrentFormat(String format)
    {
        if(format == null || format.equals(""))
        {
            format = "yyyy-MM-dd";
        }
        LocalDate currentDate = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
        String formattedDate = currentDate.format(formatter);
        return formattedDate;
    }

    /**
     * 根据键值获取json字符串对应的值
     * @param str
     * @param key
     * @return
     * @throws JSONException
     */
    public static String stringToJson(String str,String key) throws JSONException
    {
        if (str == null || str.equals(""))
        {
            return "";
        }
        try
        {
            JSONObject json = new JSONObject(str);
            String value = json.getString(key);
            return value;
        }
        catch (JSONException e)
        {
            System.out.println(e);
        }
        return "";
    }

    /**
     * 检查大小写
     * @param str
     * @return
     */
    public static String checkLetter(String str)
    {
        if (str.matches("[a-z]"))
        {
            return "big";
        }
        else if (str.matches("[A-Z]"))
        {
            return "samll";
        }
        else
        {
            return "no";
        }
    }

    public static List<String> usingSubstringMethod(String text, int n)
    {
        List<String> results = new ArrayList<>();
        int length = text.length();
        //for (int i = 0; i < length; i += n)
        for (int i = 0; i < length; i++)
        {
            results.add(text.substring(i, i+1));
        }
        return results;
    }

    /**
     * json字符串转对象
     * @param json
     * @param obj
     * @return
     * @param <T>
     */
    public static <T>T jsonStringToObject(String json, Class<T> obj)
    {
        // 使用Gson库将Json字符串转换为对象
        Gson gson = new Gson();
        T myClass = gson.fromJson(json, obj);
        return myClass;
    }

    /**
     * 字符串转json
     * @param str
     * @return
     * @throws JsonProcessingException
     */
    public static JsonNode strToJson(String str) throws JsonProcessingException
    {
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode rootNode = objectMapper.readTree(str); // 将JSON字符串转换为JsonNode对象
        System.out.println(rootNode.get("params"));
        return rootNode;
    }

    /**
     * 去掉字符串中两端指定字符
     * @param str 字符串
     * @param trimChar 去掉的字符
     * @return trim("***Hello, World!***", "*");
     */
    public static String trimSelf(String str, char trimChar)
    {
        if (str == null || str.isEmpty())
        {
            return str;
        }
        int start = 0, end = str.length() - 1;
        while (start <= end && str.charAt(start) == trimChar)
        {
            start++;
        }
        while (start <= end && str.charAt(end) == trimChar)
        {
            end--;
        }
        return str.substring(start, end + 1);
    }

    /**
     * map字符串转map
     * @param str           map字符串
     * @param entryNum      map中一共几个元素
     * @return
     */
    public static Map<String, String> mapStringToMap(String str,int entryNum)
    {
        str = str.substring(1, str.length() - 1);
        String[] strs = str.split(",",entryNum);
        Map<String, String> map = new HashMap<String, String>();
        for (String string : strs)
        {
            String key = string.split("=")[0].trim();
            String value = string.split("=")[1];
            map.put(key, value);
        }
        return map;
    }
}
